package com.kiki;

import java.util.*;

public class SimilarityMatrixGenerator {

    static class User {
        String name;
        Set<String> tags;

        public User(String name, String... tags) {
            this.name = name;
            this.tags = new HashSet<>(Arrays.asList(tags));
        }
    }

    // 计算Jaccard相似度：交集大小 / 并集大小
    private static double calculateSimilarity(User a, User b) {
        Set<String> intersection = new HashSet<>(a.tags);
        intersection.retainAll(b.tags);

        Set<String> union = new HashSet<>(a.tags);
        union.addAll(b.tags);

        return union.isEmpty() ? 0 : (double) intersection.size() / union.size();
    }

    // 生成对称相似度矩阵
    private static double[][] buildSimilarityMatrix(List<User> users) {
        int n = users.size();
        double[][] matrix = new double[n][n];// 创建一个n*n（对应所有用户数量）的矩阵，用于存储相似度矩阵

        for (int i = 0; i < n; i++) {
            matrix[i][i] = 1.0; // 对角线设为1
            for (int j = i+1; j < n; j++) {
                double sim = calculateSimilarity(users.get(i), users.get(j));
                matrix[i][j] = sim;
                matrix[j][i] = sim; // 对称赋值
            }
        }
        return matrix;
    }

    // 格式化输出矩阵
    private static void printMatrix(List<User> users, double[][] matrix) {
        // 确定列宽：最大用户名长度+2
        int maxNameLength = users.stream()
                .mapToInt(u -> u.name.length())
                .max()
                .orElse(8);
        int colWidth = Math.max(maxNameLength + 2, 10);

        // 打印表头
        System.out.printf("%-" + colWidth + "s", "");
        for (User u : users) {
            System.out.printf("%-" + colWidth + "s", u.name);
        }
        System.out.println();

        // 打印数据行
        for (int i = 0; i < users.size(); i++) {
            System.out.printf("%-" + colWidth + "s", users.get(i).name);
            for (int j = 0; j < users.size(); j++) {
                System.out.printf("%-" + colWidth + ".2f", matrix[i][j]);
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        // 创建测试用户（用户名 + 兴趣标签）
        List<User> users = Arrays.asList(
                new User("张三", "编程", "游戏", "动漫"),
                new User("李四", "电影", "音乐", "运动"),
                new User("王五", "编程", "算法", "机器学习"),
                new User("赵六", "游戏", "动漫", "电影")
        );

        // 构建相似度矩阵
        double[][] matrix = buildSimilarityMatrix(users);

        // 打印矩阵
        printMatrix(users, matrix);
    }
}
